package org.rcy.framework.rpc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class NetUtils {
	
	private static Logger logger = LoggerFactory.getLogger(NetUtils.class);
	
	private static String SERVICE_IP;
	
	public static String getServerIp() {
		if(SERVICE_IP == null) {
			SERVICE_IP = detectServerIp();
		}
		return SERVICE_IP;
	}

	private static String detectServerIp() {
		long t1 = System.currentTimeMillis();
		int count =0;
		String serverIp = "127.0.0.1";
		// 一个主机有多个网络接口
		try {
			Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface netInterface = netInterfaces.nextElement();
				// 每个网络接口,都会有多个"网络地址",比如一定会有lookback地址,会有siteLocal地址等.以及IPV4或者IPV6 .
				Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
				while (addresses.hasMoreElements()) {
					count++;
					InetAddress address = addresses.nextElement();
					if (address instanceof Inet6Address) {
						continue;
					}
					if (address.isSiteLocalAddress() && !address.isLoopbackAddress()) {
						serverIp = address.getHostAddress();
						//logger.info("detected server ip :" + serverIp);
						continue;
					}
				}
			}
		} catch (SocketException e) {
			logger.error("rpc get ip error {}",e.getMessage(),e);
		}
		logger.info("rpc get ip loop {} times cost {}ms",count,(System.currentTimeMillis()-t1));
		return serverIp;
	}
	
}